package cn.javaxc.mvcwork.modules.file;
import cn.javaxc.mvcwork.controller.MVCConstant;
import cn.javaxc.mvcwork.framework.beans.TFormBean;
import cn.javaxc.model.base.*;

import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.util.helper.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;





public class FileItem extends TFormBean {

  public final static String fs = System.getProperty("file.separator");

  private String linkModuleId =null;
  private Object linkItemId = null;
  private Object id = -1;
  private int folderId = -1;
  private String subject = "";
  private String clientFilename = "";
  private String filename = "";
  private String directory = "";
  private int size = 0;
  private double version = 0;
  private String image = null;
  private boolean enabled = false;
  private boolean defaultFile = false;

  private boolean doVersionInsert = true;
  private int downloads = 0;

  private java.sql.Timestamp entered = null;
  private int enteredBy = -1;

  private java.sql.Timestamp modified = null;
  private int modifiedBy = -1;

  private FileItemVersionList versionList = null;

  private String thumbnailFilename = null;

  private boolean allowPortalAccess = false;



  
  public FileItem() {
  }


  
  public FileItem( Object itemId)  {
    queryRecord( itemId);
  }


  

  public FileItem( Object itemId, Object moduleItemId, Object moduleId)  {
    setLinkModuleId(moduleId);
    this.linkItemId = moduleItemId;
    queryRecord( itemId);
  }

  
  public FileItem( String fileName, Object moduleItemId, Object moduleId)  {
    setLinkModuleId(moduleId);
    this.linkItemId = moduleItemId;
    this.filename = fileName;
    queryRecord( -1);
  }


  

  public FileItem( Object moduleItemId, Object moduleId)  {
    setLinkModuleId(moduleId);
    this.linkItemId = moduleItemId;
    queryRecord( -1);
  }


  
  private void queryRecord( Object itemId)  {
    StringBuffer sql = new StringBuffer();
    sql.append(
        "SELECT f.*, t.filename AS thumbnail " +
        "FROM ts_files f " +
        "LEFT JOIN ts_files_thumbnail t ON (f.item_id = t.item_id AND f.version = t.version) " +
        "WHERE f.item_id > 0 ");
    if (SQL.isNotNull(itemId)) {
      sql.append("AND f.item_id = ? ");
    }
    if (SQL.isNotNull(linkModuleId)) {
      sql.append("AND f.link_module_id = ? ");
    }
    if (SQL.isNotNull(linkItemId)) {
      sql.append("AND f.link_item_id = ? ");
    }
    if (!filename.equals("")) {
      sql.append("AND client_filename like ? ");
    }
    SQLMap pst = FrameHelper.getBaseSQL().createStatement(sql.toString());//.log(new SQLLog());
    int i = 0;
    if (SQL.isNotNull(itemId)) {
      pst.setObject(++i, itemId);
    }
    if (SQL.isNotNull(linkModuleId)) {
      pst.setString(++i, linkModuleId);
    }
    if (SQL.isNotNull(linkItemId)) {
      pst.setObject(++i, linkItemId);
    }
    if (!filename.equals("")) {
      pst.setString(++i, filename);
    }
    SQLList<SQLMap> list= pst.executeQuery(null,null);
    if (list.size()>0) {
      buildRecord(list.get(0), false);
    } else {
      throw new RuntimeException("File record not found.");
    }
  }


  
  public FileItem(SQLMap rs)  {
    buildRecord(rs, false);
  }


  
  public FileItem(SQLMap rs, boolean isVersion)  {
    buildRecord(rs, isVersion);
  }


  
  public final static String getDatePath(java.sql.Timestamp fileDate) {
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy");
    String datePathToUse1 = formatter1.format(fileDate);
    SimpleDateFormat formatter2 = new SimpleDateFormat("MMdd");
    String datePathToUse2 = formatter2.format(fileDate);
    return datePathToUse1 + fs + datePathToUse2 + fs;
  }


  
  public static String getDatePath(String filenameDate) {
    if (filenameDate.length() > 7) {
      return (filenameDate.substring(0, 4) + fs +
          filenameDate.substring(4, 8) + fs);
    } else {
      return null;
    }
  }


  
  public String getFullFilePath() {
    if ("".equals(directory)) {
      return filename;
    } else {
      if (getModified() != null) {
        return directory + getDatePath(getModified()) + filename;
      } else {
        return directory + getDatePath(filename) + filename;
      }
    }
  }


  
  public void setLinkModuleId(Object tmp) {
	  if (SQL.isNotNull(tmp)){
		linkModuleId = tmp+"";  
	  }
    
  }




  
  public void setLinkItemId(Object tmp) {
    linkItemId = tmp;
  }




  
  public void setId(int tmp) {
    this.id = tmp;
  }


  
  public void setId(String tmp) {
    this.id = Integer.parseInt(tmp);
  }


  
  public void setFolderId(int tmp) {
    this.folderId = tmp;
  }


  
  public void setFolderId(String tmp) {
    this.folderId = Integer.parseInt(tmp);
  }


  
  public void setSubject(String tmp) {
    this.subject = tmp;
  }


  
  public void setClientFilename(String tmp) {
    this.clientFilename = tmp;
  }


  
  public void setFilename(String tmp) {
    this.filename = tmp;
  }


  
  public void setDirectory(String tmp) {
    this.directory = tmp;
  }


  
  public void setSize(int tmp) {
    this.size = tmp;
  }


  
  public void setSize(String tmp) {
    this.size = Integer.parseInt(tmp);
  }


  
  public void setVersion(double tmp) {
    this.version = tmp;
  }


  
  public void setVersion(String tmp) {
    this.version = Double.parseDouble(tmp);
  }


  
  public void setImage(String tmp) {
    this.image = tmp;
  }


  
  public void setEntered(java.sql.Timestamp tmp) {
    this.entered = tmp;
  }


  
  public void setEntered(String tmp) {
    this.entered = DatabaseUtils.parseTimestamp(tmp);
  }


  
  public void setEnteredBy(int tmp) {
    this.enteredBy = tmp;
  }


  
  public void setEnteredBy(String tmp) {
    this.enteredBy = Integer.parseInt(tmp);
  }


  
  public void setModified(java.sql.Timestamp tmp) {
    this.modified = tmp;
  }


  
  public void setModified(String tmp) {
    this.modified = DatabaseUtils.parseTimestamp(tmp);
  }


  
  public void setModifiedBy(int tmp) {
    this.modifiedBy = tmp;
  }


  
  public void setModifiedBy(String tmp) {
    this.modifiedBy = Integer.parseInt(tmp);
  }


  
  public void setEnabled(boolean tmp) {
    this.enabled = tmp;
  }


  
  public void setEnabled(String tmp) {
    this.enabled = ("on".equalsIgnoreCase(tmp) || "true".equalsIgnoreCase(tmp));
  }


  
  public void setDefaultFile(boolean tmp) {
    this.defaultFile = tmp;
  }


  
  public void setDefaultFile(String tmp) {
    defaultFile = DatabaseUtils.parseBoolean(tmp);
  }


  
  public boolean getDefaultFile() {
    return defaultFile;
  }


  
  public void setDownloads(int tmp) {
    downloads = tmp;
  }


  
  public void setDownloads(String tmp) {
    downloads = Integer.parseInt(tmp);
  }


  
  public void setDoVersionInsert(boolean tmp) {
    this.doVersionInsert = tmp;
  }


  
  public void setDoVersionInsert(String tmp) {
    doVersionInsert = DatabaseUtils.parseBoolean(tmp);
  }


  
  public void setThumbnailFilename(String tmp) {
    this.thumbnailFilename = tmp;
  }


  
  public boolean getDoVersionInsert() {
    return doVersionInsert;
  }


  
  public String getLinkModuleId() {
    return linkModuleId;
  }


  
  public Object getLinkItemId() {
    return linkItemId;
  }


  
  public Object getId() {
    return id;
  }


  
  public int getFolderId() {
    return folderId;
  }


  
  public String getSubject() {
    return subject;
  }


  
  public String getClientFilename() {
    return clientFilename;
  }


  
  public String getExtension() {
    return getExtension(clientFilename);
  }


  
  public static String getExtension(String clientFilename) {
    if (clientFilename.indexOf(".") > 0) {
      return clientFilename.substring(clientFilename.lastIndexOf(".")).toLowerCase();
    } else {
      return "";
    }
  }


  
  public String getFilename() {
    return filename;
  }


  
  public String getDirectory() {
    return directory;
  }


  
  public int getSize() {
    return size;
  }


  
  public int getRelativeSize() {
    int newSize = (size / 1000);
    if (newSize == 0) {
      return 1;
    } else {
      return newSize;
    }
  }


  
  public double getVersion() {
    return version;
  }


  
  public boolean hasVersion(double version) {
    return (getVersion(version) != null ? true : false);
  }


  
  public FileItemVersion getVersion(double version) {
    if (versionList != null) {
      Iterator versions = this.versionList.iterator();
      while (versions.hasNext()) {
        FileItemVersion thisVersion = (FileItemVersion) versions.next();
        if (thisVersion.getVersion() == version) {
          return thisVersion;
        }
      }
    }
    return null;
  }


  
  public String getVersionNextMajor() {
    return (((int) version + 1) + ".0");
  }


  
  public String getVersionNextMinor() {
    String value = String.valueOf(version);
    if (value.indexOf(".") > -1) {
      value = value.substring(0, value.indexOf(".") + 2);
    }

    String newVersion = (new java.math.BigDecimal(value).add(
        new java.math.BigDecimal(".1"))).toString();
    if (Double.parseDouble(newVersion) > (Double.parseDouble(
        getVersionNextMajor()))) {
      return getVersionNextMajor();
    } else {
      return newVersion;
    }
  }


  
  public String getVersionNextChanges() {
    String newVersion = (new java.math.BigDecimal("" + version).add(
        new java.math.BigDecimal(".01"))).toString();
    return newVersion;
  }


  
  public String getImage() {
    return image;
  }


  
  public String getImageTag() {
    return getImageTag("");
  }


  
  public String getImageTag(String imageExt) {
    return getImageTag(image, imageExt, getExtension());
  }


  
  public static String getImageTag(String image, String imageExt, String ext) {
    if (image == null) {
      if (".bmp".equals(ext)) {
        image = "gnome-image-bmp";
      } else if (".dia".equals(ext)) {
        image = "gnome-application-x-dia-diagram";
      } else if (".doc".equals(ext)) {
        image = "gnome-application-msword";
      } else if (".eps".equals(ext)) {
        image = "gnome-application-encapsulated_postscript";
      } else if (".gif".equals(ext)) {
        image = "gnome-image-gif";
      } else if (".gz".equals(ext)) {
        image = "gnome-compressed";
      } else if (".gzip".equals(ext)) {
        image = "gnome-compressed";
      } else if (".html".equals(ext)) {
        image = "gnome-text-html";
      } else if (".jar".equals(ext)) {
        image = "gnome-application-x-jar";
      } else if (".java".equals(ext)) {
        image = "gnome-application-x-java-source";
      } else if (".jpeg".equals(ext)) {
        image = "gnome-image-jpeg";
      } else if (".jpg".equals(ext)) {
        image = "gnome-image-jpeg";
      } else if (".midi".equals(ext)) {
        image = "gnome-audio-midi";
      } else if (".mp3".equals(ext)) {
        image = "gnome-audio-mpg";
      } else if (".mpeg".equals(ext)) {
        image = "gnome-video-mpeg";
      } else if (".mpg".equals(ext)) {
        image = "gnome-video-mpeg";
      } else if (".pdf".equals(ext)) {
        image = "gnome-application-pdf";
      } else if (".png".equals(ext)) {
        image = "gnome-image-png";
      } else if (".ppt".equals(ext)) {
        image = "gnome-application-vnd.ms-powerpoint";
      } else if (".psd".equals(ext)) {
        image = "gnome-image-psd";
      } else if (".ps".equals(ext)) {
        image = "gnome-application-postscript";
      } else if (".sql".equals(ext)) {
        image = "gnome-text-x-sql";
      } else if (".sdc".equals(ext)) {
        image = "gnome-application-x-generic-spreadsheet";
      } else if (".sdd".equals(ext)) {
        image = "gnome-application-x-staroffice-presentation";
      } else if (".sdw".equals(ext)) {
        image = "gnome-application-x-staroffice-words";
      } else if (".sxc".equals(ext)) {
        image = "gnome-application-x-generic-spreadsheet";
      } else if (".sxd".equals(ext)) {
        image = "gnome-application-x-openoffice-presentation";
      } else if (".sxw".equals(ext)) {
        image = "gnome-application-x-openoffice-words";
      } else if (".tgz".equals(ext)) {
        image = "gnome-compressed";
      } else if (".tif".equals(ext)) {
        image = "gnome-image-tiff";
      } else if (".tiff".equals(ext)) {
        image = "gnome-image-tiff";
      } else if (".wav".equals(ext)) {
        image = "gnome-audio-x-wav";
      } else if (".xls".equals(ext)) {
        image = "gnome-application-vnd.ms-excel";
      } else if (".zip".equals(ext)) {
        image = "gnome-compressed";
      } else {
        image = "gnome-text-plain";
      }
    }
    return "<img border=\"0\" src=\"images/mime/" + image + imageExt + ".gif\" align=\"absmiddle\" alt=\"" + "" + "\">";
  }



  
  public java.sql.Timestamp getEntered() {
    return entered;
  }


  
  public String getEnteredString() {
    try {
      return DateFormat.getDateInstance(3).format(entered);
    } catch (NullPointerException e) {
    }
    return "";
  }


  
  public String getEnteredDateTimeString() {
    try {
      return DateFormat.getDateTimeInstance(3, 3).format(entered);
    } catch (NullPointerException e) {
    }
    return "";
  }


  
  public int getEnteredBy() {
    return enteredBy;
  }


  
  public java.sql.Timestamp getModified() {
//    return modified;
	return getEntered();
  }


  
  public String getModifiedString() {
    try {
      return DateFormat.getDateInstance(3).format(modified);
    } catch (NullPointerException e) {
    }
    return "";
  }


  
  public String getModifiedDateTimeString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(
          modified);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public Timestamp getModificationDate() {
    if (modified != null) {
      return modified;
    }
    if (entered != null) {
      return entered;
    }
    return new Timestamp((new java.util.Date()).getTime());
  }


  
  public int getModifiedBy() {
    return modifiedBy;
  }


  
  public int getDownloads() {
    return downloads;
  }


  
  public boolean getEnabled() {
    return enabled;
  }


  
  public FileItemVersionList getVersionList() {
    return versionList;
  }


  
  public String getThumbnailFilename() {
    return thumbnailFilename;
  }


  
  public boolean getAllowPortalAccess() {
    return allowPortalAccess;
  }


  
  public void setAllowPortalAccess(boolean allowPortalAccess) {
    this.allowPortalAccess = allowPortalAccess;
  }

  
  public void setAllowPortalAccess(String tmp) {
    allowPortalAccess = DatabaseUtils.parseBoolean(tmp);
  }

  
  public boolean insert() throws Exception {
    boolean result = true;
	
//      StringBuffer sql = new StringBuffer();
//      sql.append(
//          "INSERT INTO\n ts_files " +
//          "(folder_id, subject, client_filename, filename, version, size, enabled, downloads, ");
//      if (SQL.isNotNull(id)) {
//        sql.append("item_id, ");
//      }
//      sql.append("entered, ");
//      sql.append(
//          " link_module_id, link_item_id, enteredBy, modifiedBy, default_file, allow_portal_access, modified)\n " +
//          "VALUES (:folder_id, :subject, :client_filename, :filename, :version, :size, :enabled, :downloads, ");
//      if (SQL.isNotNull(id)) {
//        sql.append(":item_id, ");
//      }
//      if (entered != null) {
//        sql.append(":entered, ");
//      } else {
//        sql.append("CURRENT_TIMESTAMP, ");
//      }
//      sql.append(":link_module_id, :link_item_id, :enteredBy, :modifiedBy, :default_file, :allow_portal_access, " + ((this.getModified() != null) ? ":modified" :  "CURRENT_TIMESTAMP") + ") ");

      SQLMap emt=new SQLMap();
      emt.setInt("folder_id", folderId);
      emt.setString("subject", subject);
      emt.setString("client_filename", clientFilename);
      emt.setString("filename", filename);
      emt.setDouble("version", version);
      emt.setInt("size", size);
      emt.setBoolean("enabled", enabled);
      emt.setInt("downloads", downloads);
      if (SQL.isNotNull(id)) {
        emt.setObject("item_id", id);
      }
      if (entered != null) {
        emt.setTimestamp("entered", entered);
      }
      emt.setString("link_module_id", linkModuleId);
      emt.setObject("link_item_id", linkItemId);
      emt.setInt("enteredBy", enteredBy);
      emt.setInt("modifiedBy", modifiedBy);
      emt.setBoolean("default_file", defaultFile);
      emt.setBoolean("allow_portal_access", allowPortalAccess);
      if (this.getModified() != null) {
        emt.setTimestamp("modified", this.getModified());
      }
//		id = emt.insert(sql.toString());
		IBaseDAO dao=FrameHelper.getBaseDAO();
		id =dao.insertFileItem(emt);

      // Insert the version information
      if (doVersionInsert) {
        FileItemVersion thisVersion = new FileItemVersion();
        thisVersion.setItemId(this.getId());
        thisVersion.setSubject(subject);
        thisVersion.setClientFilename(clientFilename);
        thisVersion.setFilename(filename);
        thisVersion.setVersion(version);
        thisVersion.setSize(size);
        thisVersion.setAllowPortalAccess(allowPortalAccess);
        thisVersion.setEnteredBy(enteredBy);
        thisVersion.setModifiedBy(modifiedBy);
        thisVersion.insert();
      }

    return result;
  }


  
  public boolean insertVersion() throws Exception {
    boolean result = true;
      //Insert a new version of an existing file
      FileItemVersion thisVersion = new FileItemVersion();
      thisVersion.setItemId(this.getId());
      thisVersion.setSubject(subject);
      thisVersion.setClientFilename(clientFilename);
      thisVersion.setFilename(filename);
      thisVersion.setVersion(version);
      thisVersion.setSize(size);
      thisVersion.setEnteredBy(enteredBy);
      thisVersion.setModifiedBy(modifiedBy);
      thisVersion.setAllowPortalAccess(allowPortalAccess);
      thisVersion.insert();
      
//      String sql="UPDATE ts_files \n"+
//	"SET subject = :subject, client_filename = :client_filename, filename = :filename, version = :version, \n"+
//	"size = :size, modifiedBy = :modifiedBy, \n"+
//	"modified = CURRENT_TIMESTAMP \n"+
//	", allow_portal_access = :allow_portal_access \n"+
//	"WHERE item_id = :item_id ";
	  SQLMap emt=new SQLMap();
      emt.setString("subject", subject);
      emt.setString("client_filename", clientFilename);
      emt.setString("filename", filename);
      emt.setDouble("version", version);
      emt.setInt("size", size);
      emt.setInt("modifiedBy", modifiedBy);
      emt.setBoolean("allow_portal_access", allowPortalAccess);
      emt.setObject("item_id", this.getId());
//	  emt.execute(sql.toString());
	  IBaseDAO dao=FrameHelper.getBaseDAO();
	  dao.updateFileVersion(emt);
	  //Update the master record
//      SpringStatement pst = new SpringStatement(sql);
//      pst.execute(null);
//      
		
    return result;
  }


  



  
  public boolean updateCounter()  {
    FileDownloadLog thisLog = new FileDownloadLog();
    thisLog.setItemId(id);
    thisLog.setVersion(version);
    thisLog.setUserId(enteredBy);
    thisLog.setFileSize(size);
    return thisLog.updateCounter();
  }


  
  public boolean buildVersionList()  {
    return buildVersionList( false);
  }

  
  public boolean buildVersionList( boolean isPortalUser)  {
    if (versionList == null) {
      versionList = new FileItemVersionList();
    } else {
      versionList.clear();
    }
    if (isPortalUser) {
      versionList.setBuildPortalRecords(MVCConstant.TRUE);
    }
    versionList.setItemId(this.getId());
    versionList.buildList();
    return true;
  }



  
  public boolean delete( String baseFilePath)  {

    return true;
  }


  
  private void buildRecord(SQLMap rs, boolean isVersion)  {
    id = rs.getInt("item_id");
    if (!isVersion) {
      linkModuleId = rs.getString("link_module_id");
      linkItemId = rs.getInt("link_item_id");
      folderId = rs.getInt( "folder_id", 0);
    }
    clientFilename = rs.getString("client_filename");
    filename = rs.getString("filename");
    subject = rs.getString("subject");
    size = rs.getInt("size");
    version = rs.getDouble("version");
    enabled = rs.getBoolean("enabled");
    downloads = rs.getInt("downloads");
    entered = rs.getTimestamp("entered");
    enteredBy = rs.getInt("enteredBy");
    modified = rs.getTimestamp("modified");
    modifiedBy = rs.getInt("modifiedBy");
    allowPortalAccess = rs.getBoolean("allow_portal_access");
    if (!isVersion) {
      thumbnailFilename = rs.getString("thumbnail");
    }
    defaultFile = rs.getBoolean("default_file");
  }



  


  
  public boolean isImageFormat() {
    String extension = getExtension();
    return (".gif".equals(extension) ||
        ".jpg".equals(extension) ||
        ".png".equals(extension)
        );
  }


  
  public boolean hasThumbnail() {
    return thumbnailFilename != null;
  }  

}
